import React, { memo, useRef, FC } from 'react';
import { FormInstance } from 'antd/lib/form';
// import styles from './index.less';
import CommonModal from '@/components/CommonModal';
import AddForm from './AddForm';
import OpenCardForm from './OpenCardForm';
import { modelName } from '@/pages/Card/components/BlankCard';
import useCardModel from '@/pages/Card/useCardModel';
import { ActionType } from '@/components/ProTable';
import { ActivateCardParamsType, AddCardParamsType } from '@/pages/Card/API';

interface Props {
  actionRef: React.MutableRefObject<ActionType | undefined>;
  normalActionRef: React.MutableRefObject<ActionType | undefined>;
}

const ModalContent: FC<Props> = (props) => {
  const { actionRef, normalActionRef } = props;
  const formRef = useRef<FormInstance>();
  const { addCard, activateCard, cardInfo } = useCardModel((model) => [
    model.addCard,
    model.cardInfo,
  ]);

  const confim = async <T extends {}>(
    cancel: () => void,
    request: (params: T) => Promise<any>,
    filterData?: (props: any) => Promise<any>,
    isOpenCard?: boolean,
  ) => {
    try {
      const fields: any = await formRef.current?.validateFields();
      const params = await (filterData ? filterData(fields) : fields);
      let res = await request(params);
      if (res.result === 0) {
        await actionRef.current?.reload();
        await (isOpenCard && normalActionRef.current?.reload());
        cancel();
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };
  return (
    <>
      <CommonModal
        title="开卡"
        width={600}
        confirmLoading={false}
        type={modelName + 'open-card'}
        onOk={(cancelModal: (type?: string, clear?: boolean) => void) => {
          const filterData = async (fields: any) => {
            delete fields['cardNo'];
            delete fields['cardType'];
            return { ...fields, id: cardInfo?.id };
          };
          confim<ActivateCardParamsType>(cancelModal, activateCard, filterData, true);
        }}
      >
        <OpenCardForm formRef={formRef} />
      </CommonModal>
      <CommonModal
        title="新增"
        width={600}
        confirmLoading={false}
        type={modelName + 'add'}
        onOk={(cancelModal: (type?: string, clear?: boolean) => void) => {
          confim<AddCardParamsType>(cancelModal, addCard);
        }}
      >
        <AddForm formRef={formRef} />
      </CommonModal>
    </>
  );
};

export default memo(ModalContent);
